import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
import vuexPersist  from "vuex-persist";
export default new Vuex.Store({
  state: {
    shoplist:[],
  },
  mutations: {
    // 加入购物车
    add(state,i){
      var flag =false;
      state.shoplist.forEach((item) => {
        if(item.cid==i.cid){
          flag=true;
          item.num++;
        }
      });
      if(flag==false){
        i.num=1;
        state.shoplist.push(i);
      }
    },
    // 加
    jia(state,id){
     state.shoplist.forEach((item)=>{
       if(item.cid==id){
         item.num++;
       }
     })
    },
    // 减
    jian(state,id){
     state.shoplist.forEach((item)=>{
       if(item.cid==id){
         item.num--;
       }
     })
    },
    // 清空购物车
    clear(state){
      state.shoplist=[];
    }
  },
    //计算总价
  getters: {
    sum(state) {
        let res = 0;
        state.shoplist.forEach((item) => {
            res += item.price * item.num;
        });
        return res;
    },
},
  actions: {
  },
  modules: {
  },
  plugins: [
    new vuexPersist({
      storage: window.localStorage,
    }).plugin,
  ],
})